﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;

class GameManager : MonoBehaviour
{
    public static GameManager Instance;
    [SerializeField] PauseMenu pauseMenu;
    public bool IsPlaying { get; set; } = false;
    public bool IsSinglePlay { get; private set; } = true;
    private void Awake()
    {
        if (Instance == null)
            Instance = this;
        else
            Destroy(gameObject);
        
        //初始加载菜单场景
        MySceneManager.Instance.LoadSceneAsync("Menu");
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape) && IsPlaying)
        {
            pauseMenu.OnHandleInput();
        }
    }

    public void StartSingleGame()
    {
        IsPlaying = true;
        IsSinglePlay = true;
        ConnectionManager.Instance.StartHost("","",1);
        MySceneManager.Instance.LoadSceneByNet("Level");
    }

    IEnumerator SetPlayerStateCoroutine(bool state)
    {
        //等待一帧，确保RPC能被发送
        yield return null;
        if (MultiPlayManager.Instance != null)
            MultiPlayManager.Instance.SetPlayStateRpc(state);
    }

    public void StartMultiGame()
    {        
        IsSinglePlay = false;
        MySceneManager.Instance.LoadSceneByNet("Level");
        StartCoroutine(SetPlayerStateCoroutine(true));
    }    

    public void GameOver()
    {        
        if (IsSinglePlay)
        {
            IsPlaying = false;
            Debug.Log("Game Over On Single");
            ConnectionManager.Instance.ShutDown();            
        }
        else
        {
            Debug.Log("Game Over On MultiPlay");
            MySceneManager.Instance.LoadSceneByNet("Lobby");
            StartCoroutine(SetPlayerStateCoroutine(false));
        }
    }
}
